package com.xjm.service.serviceImpl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjm.entity.dto.MenuDto;
import com.xjm.entity.model.MenuModel;
import com.xjm.entity.vo.MenuVo;
import com.xjm.excption.AppException;
import com.xjm.mapper.MenuMapper;
import com.xjm.service.MenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;

@Service
@RequiredArgsConstructor
public class MenuServiceImpl extends ServiceImpl<MenuMapper, MenuModel> implements MenuService {

    private final MenuMapper menuMapper;

    @Override
    public List<MenuVo> getList() {
        List<MenuVo> menuVos = BeanUtil.copyToList(menuMapper.selectList(null), MenuVo.class);
        return getChildren(0, menuVos);
    }

    @Override
    public List<MenuVo> getAdminList(Integer adminId) {
        //后期权限加上在使用adminId
        LambdaQueryWrapper<MenuModel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MenuModel::getStatus, 1);
        List<MenuVo> menuVos = BeanUtil.copyToList(menuMapper.selectList(wrapper), MenuVo.class);
        return getChildren(0, menuVos);
    }

    @Override
    public Integer addMenu(MenuDto menuDto) {
        MenuModel menuModel = new MenuModel();
        BeanUtil.copyProperties(menuDto, menuModel);
        return menuMapper.insert(menuModel);
    }

    @Override
    public MenuVo getMenuById(String id) {
        MenuVo menuVo = new MenuVo();
        MenuModel menuModel = menuMapper.selectById(id);
        if (menuModel == null) {
            throw new AppException("菜单不存在");
        }
        BeanUtil.copyProperties(menuModel, menuVo);
        return menuVo;
    }

    @Override
    public Boolean updateMenu(MenuDto menuDto) {
        MenuModel menuModel = new MenuModel();
        BeanUtil.copyProperties(menuDto, menuModel);
        return menuMapper.updateById(menuModel) != 0;
    }

    @Override
    public boolean deleteMenu(String id) {
        LambdaQueryWrapper<MenuModel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MenuModel::getPid, id);
        if (menuMapper.selectCount(wrapper) != 0) {
            throw new AppException("该菜单下存在子菜单，无法删除");
        }
        return menuMapper.deleteById(id) != 0;
    }

    // 递归查询子菜单
    private List<MenuVo> getChildren(int pid, List<MenuVo> menuVos) {
        for (MenuVo menuVo : menuVos) {
            if (menuVo.getPid() == pid) {
                menuVo.setChildren(getChildren(menuVo.getId(), menuVos));
            }
        }
        return menuVos.stream()
                .filter(menuVo -> menuVo.getPid() == pid)
                .sorted(Comparator.comparingInt(MenuVo::getSort).reversed())
                .toList();
    }
}
